const router = require('@koa/router')();
const jwt = require('../utils/jwt.js');
const { findNoteListByType, findNoteListById,notePublish } = require('../controller/index.js')
const { formateTime } = require('../utils/formateTime.js');

router.get('/findNoteListByType', jwt.verify(), async (ctx) => {
    //校验token合理再去数据库中查找数据再返回给前端
    const { note_type } = ctx.request.query
    // console.log(note_type);
    const res = await findNoteListByType(note_type, ctx.userId)
    // console.log(res);
    try {
        if (res.length) {
            ctx.body = {
                code: '800',
                data: res,
                msg: '查询成功'
            }
        } else {
            ctx.body = {
                code: '800',
                data: res,
                msg: '没有数据'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '805',
            data: error,
            msg: '服务器异常'
        }
    }
})

router.get('/findNoteListById',jwt.verify(),async(ctx)=>{
    //校验token合理再去数据库中查找数据再返回给前端
    const { note_id } = ctx.request.query
    const res = await findNoteListById(note_id)
    try {
        if (res.length) {
            ctx.body = {
                code: '800',
                data: res,
                msg: '查询成功'
            }
        } else {
            ctx.body = {
                code: '800',
                data: res,
                msg: '没有数据'
            }
        }
    } catch (error) {
        ctx.body = {
            code: '805',
            data: error,
            msg: '服务器异常'
        }
    }
})

router.post('/note-publish',jwt.verify(),async(ctx)=>{
    const { title, 
        note_type, 
        note_content, 
        head_img
        } = ctx.request.body;
    const c_time = formateTime(new Date())
    const m_time = formateTime(new Date())
    // console.log(111);
    try{
        const res = await notePublish({
            title, 
            note_type, 
            note_content, 
            head_img, 
            c_time, 
            m_time, 
            userId:ctx.userId,
            nickname:ctx.nickname
        })
        // console.log(res);
        if(res.affectedRows) {
            ctx.body = {
                code: '800',
                data: 'success',
                msg: '发布成功'
            }
        }else{
            ctx.body = {
                code: '804',
                data: 'failed',
                msg: '发布失败'
            }
        }
    }catch(error){
        ctx.body = {
            code: '805',
            data: error,
            msg: '服务器异常'
        }
    }
    
})

module.exports = router